package com.mgq.netty.chat.client;

import com.mgq.netty.chat.message.RpcRequestMessage;
import com.mgq.netty.chat.protocol.MessageCodecShare;
import com.mgq.netty.chat.protocol.ProtocolFrameDecoder;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.logging.LoggingHandler;
import lombok.extern.slf4j.Slf4j;

import java.net.InetSocketAddress;

@Slf4j
public class RpcClient {
    public static void main(String[] args) {

        initChannel();
    }

    private static void  initChannel() {
        NioEventLoopGroup group = new NioEventLoopGroup();
        LoggingHandler LOG_HANDLER = new LoggingHandler();
        MessageCodecShare MES_CODEC = new MessageCodecShare();
        RpcResponseHandler RPC_RESPONSE_CODEC = new RpcResponseHandler();

        ChannelFuture future = null;
        try {
            future = new Bootstrap()
                    .group(group)
                    .option(ChannelOption.CONNECT_TIMEOUT_MILLIS, 3000)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<NioSocketChannel>() {
                        @Override
                        protected void initChannel(NioSocketChannel ch) throws Exception {
                            ch.pipeline().addLast(new ProtocolFrameDecoder());
                            ch.pipeline().addLast(LOG_HANDLER);
                            ch.pipeline().addLast(MES_CODEC);
                            ch.pipeline().addLast(RPC_RESPONSE_CODEC);
                        }
                    }).connect(new InetSocketAddress("localhost", 8080)).sync();
        } catch (InterruptedException e) {
            log.error("error", e);
        }
        future.channel().writeAndFlush(new RpcRequestMessage(
                "com.mgq.chat.service.HelloService",
                "sayHello",
                String.class,
                new Class[]{String.class},
                new Object[]{"张三"}
        )).addListener(promise->{
            if (!promise.isSuccess()) {
                log.error("发生了错误",promise.cause());
            }
        });

        //这个位置连接已经建立
        future.channel().closeFuture().addListener(new ChannelFutureListener() {
            @Override
            public void operationComplete(ChannelFuture future) throws Exception {
                //关闭group,退出客户端
                group.shutdownGracefully();
            }
        });
    }
}
